from flask import jsonify, request
from app.models import Node, Relationship, NodeSchema, RelationshipSchema, Chart
from . import api_bp

@api_bp.route('/chain-data', methods=['GET'])
def get_chain_data():
    try:
        chart_id = request.args.get('chart_id')

        # 如果没有指定chart_id，使用默认图
        if not chart_id:
            default_chart = Chart.query.filter_by(is_default=True, status='active').first()
            if not default_chart:
                return jsonify({
                    'code': 404,
                    'message': 'No default chart found',
                    'data': None
                }), 404
            chart_id = default_chart.id

        nodes = Node.query.filter_by(chart_id=chart_id, status='active').all()
        relationships = Relationship.query.filter_by(chart_id=chart_id, status='active').all()

        nodes_schema = NodeSchema(many=True)
        relationships_schema = RelationshipSchema(many=True)

        nodes_data = nodes_schema.dump(nodes)
        relationships_data = relationships_schema.dump(relationships)

        nodes_formatted = []
        for node in nodes_data:
            nodes_formatted.append({
                'id': node['id'],
                'name': node['name'],
                'type': node['type'],
                'description': node['description'],
                'x': node['position_x'],
                'y': node['position_y'],
                'color': node['color'],
                'size': node['size']
            })

        edges_formatted = []
        for rel in relationships_data:
            edges_formatted.append({
                'id': rel['id'],
                'source': rel['upstream_node_id'],
                'target': rel['downstream_node_id'],
                'type': rel['relationship_type'],
                'label': rel['label'],
                'strength': rel['strength'],
                'color': rel['color']
            })

        return jsonify({
            'code': 200,
            'message': 'success',
            'data': {
                'nodes': nodes_formatted,
                'edges': edges_formatted
            }
        })
    except Exception as e:
        return jsonify({
            'code': 500,
            'message': str(e),
            'data': None
        }), 500